//
//  LEUtil.m
//  YouTiaoMovie
//
//  Created by jun on 2019/6/19.
//  Copyright © 2019 lechen. All rights reserved.
//

#import "LEUtil.h"
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import<AdSupport/AdSupport.h>
#import "BRPickerView.h"

@implementation LEUtil

+(NSDate *)getLaterDateFromDate:(NSDate *)date withMonth:(NSInteger)month{
    NSDateComponents *comps = [[NSDateComponents alloc]init];
    [comps setMonth:month];
    NSCalendar *calender = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *mDate = [calender dateByAddingComponents:comps toDate:date options:0];
    return mDate;
}

+ (NSString *)userInfoPath{
    NSString *pathDucment = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
    NSString *createPath = [NSString stringWithFormat:@"%@/UserInformation",pathDucment];
    if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [createPath stringByAppendingPathComponent:@"userInfor.data"];
}

+ (NSString *)modelInfoPath{
    NSString *pathDucment = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
    NSString *createPath = [NSString stringWithFormat:@"%@/UserInformation",pathDucment];
    if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [createPath stringByAppendingPathComponent:@"modelInfo.data"];
}

+(NSString *)MD5:(NSString *)mdStr
{
    const char *original_str = [mdStr UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_LONG len = (CC_LONG)strlen(original_str);
    CC_MD5(original_str, len, result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [hash appendFormat:@"%02X", result[i]];
    return [hash lowercaseString];
}

+ (BOOL)isChinaMobile:(NSString *)phoneNum
{
    NSPredicate* phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"1[345789]([0-9]){9}"];
    return [phoneTest evaluateWithObject:phoneNum];
}




+(BOOL)judgePassWordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 8 && [pass length] <= 16){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}

+(NSString*)longdate2Time:(long)ms{
    NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:ms/1000];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    return [dateFormatter stringFromDate:timeDate];
}

+(NSString*)longdate2Month:(long)ms{
    NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:ms];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月"];
    return [dateFormatter stringFromDate:timeDate];
}


+(NSString*)longdate2Detail:(long)ms{
    NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:(ms)];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags =   NSCalendarUnitYear |
    NSCalendarUnitMonth |
    NSCalendarUnitDay |
    NSCalendarUnitWeekday |
    NSCalendarUnitHour |
    NSCalendarUnitMinute;
    comps = [calendar components:unitFlags fromDate:timeDate];
    NSInteger week = [comps weekday];
    NSInteger year=[comps year];
    NSInteger month = [comps month];
    NSInteger day = [comps day];
    NSInteger hour = [comps hour];
    NSInteger minute = [comps minute];
    NSString *zeroValue = @"0";
    NSString *emptyValue = @"";
    NSString *yearMonthDay = [NSString stringWithFormat:@"%ld-%@%ld-%@%ld",(long)year,month<10?zeroValue:emptyValue,(long)month,day<10?zeroValue:emptyValue,(long)day];
    NSArray *weeks = @[@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六"];
    NSString *weekStr = [NSString stringWithFormat:@"(%@)",weeks[week-1]];
    NSString *pmStr = [NSString stringWithFormat:@"%@",hour<12?@"上午":@"下午"];
    NSString *hourMin = [NSString stringWithFormat:@"%@%ld:%@%ld", hour<10?zeroValue:emptyValue,(long)hour,
                         minute<10?zeroValue:emptyValue,(long)minute];
    return [NSString stringWithFormat:@"%@%@,%@ %@",yearMonthDay,weekStr,pmStr,hourMin];
}

+(NSData *)zipNSDataWithImage:(UIImage *)sourceImage{
    //进行图像尺寸的压缩
    CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
    CGFloat width = imageSize.width;    //图片宽度
    CGFloat height = imageSize.height;  //图片高度
    //1.宽高大于1280(宽高比不按照2来算，按照1来算)
    if (width>1280) {
        if (width>height) {
            CGFloat scale = width/height;
            height = 1280;
            width = height*scale;
        }else{
            CGFloat scale = height/width;
            width = 1280;
            height = width*scale;
        }
        //2.高度大于1280
    }else if(height>1280){
        CGFloat scale = height/width;
        width = 1280;
        height = width*scale;
    }else{
    }
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [sourceImage drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //进行图像的画面质量压缩
    NSData *data=UIImageJPEGRepresentation(newImage, 1.0);
    if (data.length>100*1024) {
        if (data.length>1024*1024) {//1M以及以上
            data=UIImageJPEGRepresentation(newImage, 0.7);
        }else if (data.length>512*1024) {//0.5M-1M
            data=UIImageJPEGRepresentation(newImage, 0.8);
        }else if (data.length>200*1024) {
            //0.25M-0.5M
            data=UIImageJPEGRepresentation(newImage, 0.9);
        }
    }
    return data;
}

+ (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL{
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = 1;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
    
    if(!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
    if(thumbnailImageRef!=nil)
        thumbnailImageRef = nil;
    
    return thumbnailImage;
}

+ (NSString *)timeFormateWithTime:(NSInteger)time formate:(NSString *)formate is:(BOOL)is {
    NSTimeInterval interval = is ? time : time/1000;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formate];
    NSString *dateString = [formatter stringFromDate: date];
    return dateString;
}

+(BOOL)isEmpty:(NSString*)text{
    NSString *rtStr = [self nullToString:text];
    return [rtStr isEqualToString:@""];
}

+ (NSString *)nullToString:(id)string {
    if ([string isEqual:@"NULL"] || [string isKindOfClass:[NSNull class]] || [string isEqual:[NSNull null]] || [string isEqual:NULL] || [[string class] isSubclassOfClass:[NSNull class]] || string == nil || string == NULL || [string isKindOfClass:[NSNull class]] || [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0 || [string isEqualToString:@"<null>"] || [string isEqualToString:@"(null)"]) {
        return @"";
    } else {
        return (NSString *)string;
    }
}

+(NSString *)getRandomStringWithNum:(NSInteger)num
{
    NSString *string = [[NSString alloc]init];
    for (int i = 0; i < num; i++) {
        int number = arc4random() % 36;
        if (number < 10) {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
        }else {
            int figure = (arc4random() % 26) + 97;
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            string = [string stringByAppendingString:tempString];
        }
    }
    return string;
}

+ (BOOL)isUserNotificationEnable{
    BOOL isEnable = NO;
    
    UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
    isEnable = (UIUserNotificationTypeNone == setting.types) ? NO : YES;
    return isEnable;
}

+(NSString *)fileSizeWithInterge:(NSInteger)size{
    // 1k = 1024, 1m = 1024k
    if (size < 1024){// 小于1k
        return [NSString stringWithFormat:@"%ldB",(long)size];
    }else if (size < 1024 * 1024){// 小于1m
        CGFloat aFloat = size/1024;
        return [NSString stringWithFormat:@"%.0fK",aFloat];
    }else if (size < 1024 * 1024 * 1024){// 小于1G
        CGFloat aFloat = size/(1024 * 1024);
        return [NSString stringWithFormat:@"%.1fM",aFloat];
    }else{CGFloat aFloat = size/(1024*1024*1024);
        return [NSString stringWithFormat:@"%.1fG",aFloat];
    }
}


+ (CGFloat)getTheStringHeight:(NSString *)string setFont:(CGFloat)font withWidth:(CGFloat)width
{
    if (string == nil || [string isEqualToString:@""])
    {
        return 0;
    }
    
    NSMutableAttributedString  *attrStr = [[NSMutableAttributedString alloc] initWithString:string];
    //段落
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    //    [paragraphStyle setLineSpacing:pageWidth];
//        paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    NSRange range = NSMakeRange(0, attrStr.length);
    [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
    //设置字体
    [attrStr addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:font]
                    range:range];
    
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];   // 获取该段
    CGSize textSize = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) // 用于计算文本绘制时占据的矩形块</span>
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                        attributes:dic        // 文字的属性
                                           context:nil].size; // context上下文。包括一些信息，例如如何调整字间距以及缩放。该对象包含的信息将用于文本绘制。该参数可为nil
    return textSize.height;
}


/// 打开外部链接
+ (void)openScheme:(NSString *)scheme {
    UIApplication *application = [UIApplication sharedApplication];
    NSURL *URL = [NSURL URLWithString:scheme];
    if (@available(iOS 10.0, *)) {
        [application openURL:URL options:@{} completionHandler:^(BOOL success) {
            NSLog(@"Open %@: %d",scheme,success);
        }];
    } else {
        // Fallback on earlier versions
        [application openURL:URL];
    }
}

+(NSString*)UUID{
    return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}

+(UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha {
    hexString = [hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    hexString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
    hexString = [hexString stringByReplacingOccurrencesOfString:@"0x" withString:@""];
    NSRegularExpression *RegEx = [NSRegularExpression regularExpressionWithPattern:@"^[a-fA-F|0-9]{6}$" options:0 error:nil];
    NSUInteger match = [RegEx numberOfMatchesInString:hexString options:NSMatchingReportCompletion range:NSMakeRange(0, hexString.length)];

    if (match == 0) {return [UIColor clearColor];}

    NSString *rString = [hexString substringWithRange:NSMakeRange(0, 2)];
    NSString *gString = [hexString substringWithRange:NSMakeRange(2, 2)];
    NSString *bString = [hexString substringWithRange:NSMakeRange(4, 2)];
    unsigned int r, g, b;
    BOOL rValue = [[NSScanner scannerWithString:rString] scanHexInt:&r];
    BOOL gValue = [[NSScanner scannerWithString:gString] scanHexInt:&g];
    BOOL bValue = [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    if (rValue && gValue && bValue) {
        return [UIColor colorWithRed:((float)r/255.0f) green:((float)g/255.0f) blue:((float)b/255.0f) alpha:alpha];
    } else {
        return [UIColor clearColor];
    }
}

+(void)feedBackHeavy{
    if (@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator*impactLight = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleHeavy];
        [impactLight impactOccurred];
    } else {
     // Fallback on earlier versions
    }
}

+(void)showSingleChoice:(NSArray*)datas
            defalutIndex:(NSInteger)defalutIndex
            resultIndex:(resultSelectIndex)resultIndex{
    
    
    BRTextPickerView *stringPickerView = [[BRTextPickerView alloc]initWithPickerMode:BRTextPickerComponentSingle];
    BRPickerStyle *style = [BRPickerStyle new];
    style.topCornerRadius = 12.f;
    style.hiddenShadowLine=  YES;
    style.titleBarColor = white_color;
    style.titleLineColor = bet_line_color;
    style.hiddenTitleLabel = YES;
    style.cancelTextColor = bet_main_color;
    style.doneTextColor = bet_main_color;
    style.pickerColor = bet_bg_color;
    style.separatorColor = bet_line_color;
    style.pickerTextColor = color33;
    style.rowHeight = 46.f;
    stringPickerView.pickerStyle = style;
    stringPickerView.dataSourceArr = datas;
    stringPickerView.selectIndex = defalutIndex;
    stringPickerView.singleResultBlock = ^(BRTextModel * _Nullable model, NSInteger index) {
          NSLog(@"选择的值：%@", model.text);
//        self.mySelectIndex = index;
        if(resultIndex){
            resultIndex(index);
        }
    };
    [stringPickerView show];
}


+(void)showDateChoice:(NSString*)defaultDate title:(NSString*)title resultDate:(resultDate)resultDate{

    BRDatePickerView *datePickerView = [[BRDatePickerView alloc]init];
    datePickerView.pickerMode = BRDatePickerModeYMD;
    datePickerView.title = title;
    if(!ISEmpty(defaultDate)){
        datePickerView.selectValue = defaultDate;
    }
    datePickerView.minDate = [NSDate br_setYear:1949 month:3 day:12];
    datePickerView.maxDate = [NSDate br_setYear:2099];
    datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
        NSLog(@"选择的值：%@", selectValue);
        if(resultDate){
            resultDate(selectValue);
        }
    };
    
    BRPickerStyle *style = [BRPickerStyle new];
    style.topCornerRadius = 12.f;
    style.hiddenShadowLine=  YES;
    style.titleBarColor = white_color;
    style.titleLineColor = bet_line_color;
    style.hiddenTitleLabel = NO;
    style.cancelColor = bet_main_color;
    style.doneTextColor = bet_main_color;
    style.hiddenCancelBtn = YES;
    style.pickerColor = bet_bg_color;
    style.separatorColor = bet_line_color;
    style.pickerTextColor = color33;
    style.rowHeight = 46.f;
    datePickerView.pickerStyle = style;

    [datePickerView show];
}

@end
